# -*- coding: utf-8 -*-

# 打字速度测试

import sys, pygame, random, time
from pygame.locals import *

reload(sys)
sys.setdefaultencoding('utf-8')


def print_text(font, x, y, text, color=(255,255,255), shadow=False):
    if shadow:
        imgText = font.render(text, True, (0, 0, 0))
        screen.blit(imgText, (x - 2, y - 2))
    image = font.render(text, True, color)
    screen.blit(image, (x, y))

white = 255,255,255
purple = 255,0,255
yellow = 255,255,0
green = 0,255,0
red = 255,0,0

pygame.init()
screen = pygame.display.set_mode((600, 500))
pygame.display.set_caption("打字速度测试")
font1 = pygame.font.Font("mini.ttf", 20)
font2 = pygame.font.Font("freesansbold.ttf", 100)

key_flag = False
correct_answer = 97     # 'a'
seconds = 11
score = 0
clock_start = 0
game_over = True

clock_start = time.clock()

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            sys.exit()
        elif event.type == KEYDOWN:
            key_flag = True
        elif event.type == KEYUP:
            key_flag = False

    keys = pygame.key.get_pressed()

    if keys[K_ESCAPE]:
        sys.exit()

    if keys[K_RETURN]:
        if game_over:
            game_over = False
            score = 0
            seconds = 11
            clock_start = time.clock()

    current = 0
    if not game_over:
        current = time.clock()-clock_start

    speed = score*6
    if seconds-current <= 0:
        game_over = True
    elif current <= 10:
        if keys[correct_answer]:
            correct_answer = random.randint(97, 122)
            score += 1

    # 清屏
    screen.fill((0, 0, 200))

    print_text(font1, 0, 0, u"看看你能打多快!")
    print_text(font1, 0, 20, u"尝试坚持10s...")

    if key_flag:
        print_text(font1, 500, 0, "<key>")

    if not game_over:
        print_text(font1, 0, 80, u"时间: " + str(int(seconds-current)))

    print_text(font1, 0, 100, u"速度: " + str(speed) + u"字母/分钟")

    if game_over:
        print_text(font1, 0, 160, u"按回车键开始...")

    print_text(font2, 0, 240, chr(correct_answer-32), yellow)

    pygame.display.update()


